const axios = require('axios')
const cheerio = require('cheerio')
const fs = require('fs')
const qs = require('qs')
const DataModel = require('./model')

let dataSource = []

// 定义一个全局事务队列
let q

const categoryType = { Mobile: 'Mobile', Tablets: 'Tablets', Laptops: 'Laptops' }
const deviceStauts = ['Not Working', 'Working', 'Flawless']

const uri = barnd => `https://www.sellyt.com/sell-my-gadgets.php?brand=${barnd}`

async function parseSellBrand(params) {
  const result = []
  // 获取所有的手机品牌
  const { data } = await axios(uri(params))
  const $ = cheerio.load(data)
  $('#sellbrand > div > ul > li > a > p').each((index, elem) => {
    result.push(
      $(elem)
        .text()
        .trim()
    )
  })
  return result
}

async function filtering(params) {
  const query = qs.stringify(params)
  const { data } = await axios({
    url: `https://www.sellyt.com/filtering.php?${query}`,
    method: 'POST',
    headers: {
      ContentType: 'application/x-www-form-urlencoded'
    }
  })
  //   console.log(data);

  return data
}

async function parseModels({ model, type }) {
  const result = []
  const data = await filtering({
    model,
    type
  })
  const $ = cheerio.load(data)
  $('div > ul > li > p').each((index, elem) => {
    result.push(
      $(elem)
        .text()
        .trim()
    )
  })
  return result
}

async function parseProducts({ capacity, type }) {
  // console.log("parseProducts", capacity, type);
  const result = []
  const data = await filtering({
    capacity,
    type
  })
  const $ = cheerio.load(data)
  $('div > ul > li > a').each((index, elem) => {
    const detailUri = $(elem).attr('href')
    const pid = detailUri.split('/')[2]
    const product = $(elem)
      .find('p.text-muted')
      .text()
      .trim()
    result.push({ product, pid })
  })
  return result
}

async function parseDevicePrices(pid) {
  console.log('parseDevicePrices', pid, 'data.length', dataSource.length)
  const result = []
  for (let i = 0; i < deviceStauts.length; i++) {
    let item = deviceStauts[i]
    const query = qs.stringify({ pid, condition: item })
    const { data } = await axios({
      url: `https://www.sellyt.com/filters.php?${query}`,
      method: 'POST',
      headers: {
        ContentType: 'application/x-www-form-urlencoded'
      }
    })
    // console.log(data);
    const $ = cheerio.load(data)
    // 详细描述
    const desc = []
    $('.detail-bottom > label > div > ul > li').each((index, elem) => {
      desc.push($(elem).text())
    })
    const basePrice = $('div > label > div.price-handset.text-left.text-blue.clearfix > h2 > span').text()
    const originalAccessories = {}
    $('form > div.checkboxbtn > div:nth-child(1) > table label').each((index, elem) => {
      const key = $(elem)
        .text()
        .trim()
      const value = $(elem)
        .find('input')
        .data('val')
      originalAccessories[key] = value
    })
    const followingIssues = {}
    $('form > div.checkboxbtn > div:nth-child(1) > table label').each((index, elem) => {
      const key = $(elem)
        .text()
        .trim()
      const value =
        parseFloat(
          $(elem)
            .find('input')
            .data('val')
        ) * -1
      followingIssues[key] = value
    })
    result.push({ condition: item, basePrice, desc, originalAccessories, followingIssues })
  }
  return result
}

async function getSellBrand(params) {
  const result = await parseSellBrand(categoryType.Mobile)
  for (let i = 0; i < result.length; i++) {
    const model = new DataModel()
    model.category = categoryType.Mobile
    model.brand = result[i]
    // q.push({
    //   name: result[i],
    //   run: (cb, index) => {
    await getModels(model)
    //     cb();
    //   }
    // });
  }
}

async function getModels(params) {
  const model = new DataModel(params)
  const result = await parseModels({ type: model.category, model: model.brand })
  for (let i = 0; i < result.length; i++) {
    model.model = result[i]
    // q.push({
    // name: result[i],
    // run: (cb, index) => {
    await getProducts(model)
    // cb();
    // }
    // });
  }
}

async function getProducts(params) {
  const model = new DataModel(params)
  const result = await parseProducts({ type: model.category, capacity: model.model })
  for (let i = 0; i < result.length; i++) {
    model.product = result[i].product
    model.pid = result[i].pid
    // q.push({
    //   name: result[i].product,
    //   run: (cb, index) => {
    await getDevicePrices(model)
    // cb();
    // }
    // });
  }
}

async function getDevicePrices(params) {
  const model = new DataModel(params)
  const result = await parseDevicePrices(model.pid)
  result.forEach(item => {
    dataSource.push({ ...model, ...item })
  })
}

// 入口
async function run() {
  // const models = await parseModels();
  // const products = await parseProducts();
  // const devicePrice = await parseDevicePrices();
  // console.time("sellyt");

  // q = queue((task, callback) => {
  //   console.log("queue task", task.name);
  //   task.run(callback, task.name);
  // }, 1);

  // // 所有队列任务完成后
  // q.drain = function() {
  //   // console.timeEnd("run");
  //   if (data > 10) {
  //     console.log(data.length);
  //     fs.writeFileSync("data.json", JSON.stringify(data));
  //   }
  //   console.log("finish!!!!");
  // };
  await getSellBrand()
  fs.writeFileSync('data.json', JSON.stringify(dataSource))
  // console.timeEnd("run");
}

run()
